//
// Thes codes are modified from SqratImport of sqrat project.
//




#include "sqstdimport.h"

#include <sqstdio.h>


#if defined(_WIN32)

#include <windows.h>

#endif

typedef SQRESULT (*SQMODULELOAD)(HSQUIRRELVM v);





SQRESULT sq_importscript(HSQUIRRELVM v, const SQChar* moduleName) {

	SQChar* filename= new SQChar[scstrlen(moduleName)+4];
	scstrcpy(filename,moduleName);
	strcat(filename,_SC(".nut"));

	if(SQ_FAILED(sqstd_loadfile(v, moduleName, true))) {
		if(SQ_FAILED(sqstd_loadfile(v, filename , true))) {
			return SQ_ERROR;
		}
	}	
	sq_push(v, -2);
	sq_call(v, 1, false, true);
	return SQ_OK;
}

SQRESULT sq_importbin(HSQUIRRELVM v, const SQChar* moduleName) {
	SQMODULELOAD modLoad;

#if defined(_WIN32)
	HMODULE mod;
	mod = GetModuleHandle(moduleName);
	if(mod == NULL) {
		mod = LoadLibrary(moduleName);
		if(mod == NULL) { 
			return SQ_ERROR;
		}
	}

	modLoad = (SQMODULELOAD)GetProcAddress(mod, "sqmodule_load");
	if(modLoad == NULL) {
		return SQ_ERROR;
	}
#endif
	SQRESULT res = modLoad(v);

	return res;
}

SQRESULT sq_import(HSQUIRRELVM v) {
	const SQChar* moduleName;
	HSQOBJECT table;
	SQRESULT res = SQ_OK;
	
	SQInteger top = sq_gettop(v);
	sq_getstring(v, -2, &moduleName);
	sq_getstackobj(v, -1, &table);
	sq_addref(v, &table);

	sq_settop(v, 0); // Clear Stack
	sq_pushobject(v, table); // Push the target table onto the stack
	
	if(SQ_FAILED(sq_importscript(v, moduleName))) {
		res = sq_importbin(v, moduleName);
	}

	sq_settop(v, 0); // Clean up the stack (just in case the module load leaves it messy)
	sq_pushobject(v, table); // return the target table

	return res;
}

SQInteger sqratbase_import(HSQUIRRELVM v) {
	SQInteger args = sq_gettop(v);
	switch(args) {
		case 2:
			sq_pushroottable(v);
			break;
		case 3:
			// should already have the desired table pushed onto the stack
			break;
		default:
			// Error, unexpected number of arguments
			break;
	}

	sq_import(v);
	
	return 1;
}

SQRESULT sqstd_register_importlib(HSQUIRRELVM v) {
	sq_pushroottable(v);

	sq_pushstring(v, _SC("import"), -1);
	sq_newclosure(v, &sqratbase_import, 0);
	sq_newslot(v, -3, 0);

	sq_pop(v, 1); // pop sqrat table

	return SQ_OK;
}